<template>
  <div :class="className" :style="{height:height,width:width}" ref="chartDiv"/>
</template>

<script>
import * as echarts from 'echarts'
import {debounce} from '@/utils'
require('echarts/theme/royal') // echarts theme
import html2canvas from "html2canvas";

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    opinionSeriesData:{
      type: Array,
      default: []
    },
    saveImage: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      base64Image: undefined,
      chart: null,
      opinion: {
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        backgroundColor: '#fff',
        series: [
          {
            name: '面积模式',
            type: 'pie',
            radius: [30, 120],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8
            },
            data: this.opinionSeriesData
          }
        ]
      }
    }
  },
  mounted() {
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  watch: {
    opinionSeriesData(newValue, oldValue) {
      this.opinion.series[0].data = newValue
      this.chart.setOption(this.opinion);
    },
  },
  methods: {
    doSaveImage(){
      let element = this.$refs.chartDiv
      const p1 = new Promise((resolve, reject) => {
        html2canvas(element).then(canvas => {
          this.base64Image = canvas.toDataURL("image/png")
          this.$emit("getBase64Image",this.base64Image)
          resolve()
        }).catch(error => {
          reject(error)
        });
      })
      const p = Promise.all([p1]);
      p.then()

    },
    initChart() {
      //定义一个promise对象 在内部执行我们的表格渲染代码
      let promise = new Promise((resolve, reject) => {
        this.chart = echarts.init(this.$el, 'royal')
        this.chart.setOption(this.opinion)
        // 绑定渲染停止时触发promise完成状态
        this.chart.on('finished',() => {
          resolve();
        })

        this.__resizeHandler = debounce(() => {
          if (this.chart) {
            this.chart.resize()
          }
        }, 100)
        window.addEventListener('resize', this.__resizeHandler)
      });
      // 渲染完成后执行then()方法的操作代码
      promise.then(() => {
        if(this.saveImage){
          console.log("开始保存图片")
          this.doSaveImage();
        }
      });

    }
  }
}
</script>
